<template>
  <div class="toolbarContainer" :class="{ isDark: isDark }">
    <div class="toolbar">
      <!-- 节点操作 -->
      <div class="toolbarBlock" >
        <div class="toolbarBtn" :class="{
          disabled: readonly || backEnd
        }" @click="emit('execCommand', 'BACK')">
          <span class="icon iconfont iconhoutui-shi"></span>
          <span class="text">{{ $t('toolbar.undo') }}</span>
        </div>
        <div class="toolbarBtn" :class="{
          disabled: readonly || forwardEnd
        }" @click="emit('execCommand', 'FORWARD')">
          <span class="icon iconfont iconqianjin1"></span>
          <span class="text">{{ $t('toolbar.redo') }}</span>
        </div>
        <div class="toolbarBtn" :class="{
          disabled: activeNodes.length <= 0 || hasGeneralization,
          active: isInPainter
        }" @click="emit('startPainter')">
          <span class="icon iconfont iconjiedian"></span>
          <span class="text">{{ $t('toolbar.painter') }}</span>
        </div>
        <div class="toolbarBtn" :class="{
          disabled: activeNodes.length <= 0 || !hasRoot || hasGeneralization
        }" @click="emit('execCommand', 'INSERT_NODE')">
          <span class="icon iconfont iconjiedian"></span>
          <span class="text">{{ $t('toolbar.insertSiblingNode') }}</span>
        </div>
        <div class="toolbarBtn" :class="{
          disabled: activeNodes.length <= 0 || hasGeneralization
        }" @click="emit('execCommand', 'INSERT_CHILD_NODE')">
          <span class="icon iconfont icontianjiazijiedian"></span>
          <span class="text">{{ $t('toolbar.insertChildNode') }}</span>
        </div>
        <div class="toolbarBtn" :class="{
          disabled: activeNodes.length <= 0
        }" @click="emit('execCommand', 'REMOVE_NODE')">
          <span class="icon iconfont iconshanchu"></span>
          <span class="text">{{ $t('toolbar.deleteNode') }}</span>
        </div>
        <div class="toolbarBtn" :class="{
          disabled: activeNodes.length <= 0
        }" @click="emit('showNodeImage')">
          <span class="icon iconfont iconimage"></span>
          <span class="text">{{ $t('toolbar.image') }}</span>
        </div>
        <div class="toolbarBtn" :class="{
          disabled: activeNodes.length <= 0
        }" @click="showNodeIcon">
          <span class="icon iconfont iconxiaolian"></span>
          <span class="text">{{ $t('toolbar.icon') }}</span>
        </div>
        <div class="toolbarBtn" :class="{
          disabled: activeNodes.length <= 0
        }" @click="emit('showNodeLink')">
          <span class="icon iconfont iconchaolianjie"></span>
          <span class="text">{{ $t('toolbar.link') }}</span>
        </div>
        <div class="toolbarBtn" :class="{
          disabled: activeNodes.length <= 0
        }" @click="emit('showNodeNote')">
          <span class="icon iconfont iconflow-Mark"></span>
          <span class="text">{{ $t('toolbar.note') }}</span>
        </div>
        <div class="toolbarBtn" :class="{
          disabled: activeNodes.length <= 0
        }" @click="emit('showNodeTag')">
          <span class="icon iconfont iconbiaoqian"></span>
          <span class="text">{{ $t('toolbar.tag') }}</span>
        </div>
        <div class="toolbarBtn" :class="{
          disabled: activeNodes.length <= 0 || !hasRoot || hasGeneralization
        }" @click="emit('execCommand', 'ADD_GENERALIZATION')">
          <span class="icon iconfont icongaikuozonglan"></span>
          <span class="text">{{ $t('toolbar.summary') }}</span>
        </div>
        <!-- <div class="toolbarBtn" :class="{
          disabled: activeNodes.length <= 0 || hasGeneralization
        }" @click="emit('createAssociativeLine')">
          <span class="icon iconfont iconlianjiexian"></span>
          <span class="text">{{ $t('toolbar.associativeLine') }}</span>
        </div> -->
        <div class="toolbarBtn" :class="{
          disabled: activeNodes.length <= 0 || hasGeneralization
        }" @click="showFormula">
          <span class="icon iconfont icongongshi"></span>
          <span class="text">{{ $t('toolbar.formula') }}</span>
        </div>
      </div>
      <!-- 通用操作 -->
      <!-- <div class="toolbarBlock">
        <div class="toolbarBtn" @click="emit('showOutline')">
          <span class="icon iconfont iconfuhao-dagangshu"></span>
          <span class="text">{{ $t('toolbar.displayOutline') }}</span>
        </div>
        <div class="toolbarBtn" @click="emit('showBaseStyle')">
          <span class="icon iconfont iconyangshi"></span>
          <span class="text">{{ $t('toolbar.baseStyle') }}</span>
        </div>
        <div class="toolbarBtn" @click="emit('showTheme')">
          <span class="icon iconfont iconjingzi"></span>
          <span class="text">{{ $t('toolbar.theme') }}</span>
        </div>
        <div class="toolbarBtn" @click="emit('showStructure')">
          <span class="icon iconfont iconjiegou"></span>
          <span class="text">{{ $t('toolbar.strusture') }}</span>
        </div>
      </div> -->
      <!-- 导出 -->
      <div class="toolbarBlock" >
        <!-- <div class="toolbarBtn" @click="createNewLocalFile">
          <span class="icon iconfont iconxinjian"></span>
          <span class="text">{{ $t('toolbar.newFile') }}</span>
        </div>
    
        <div class="toolbarBtn" @click="openLocalFile">
          <span class="icon iconfont icondakai"></span>
          <span class="text">{{ $t('toolbar.openFile') }}</span>
        </div>
        <div class="toolbarBtn" @click="saveLocalFile">
          <span class="icon iconfont iconlingcunwei"></span>
          <span class="text">{{ $t('toolbar.saveAs') }}</span>
        </div> -->
        <!-- <div class="toolbarBtn" @click="emit('showImport')">
          <span class="icon iconfont icondaoru"></span>
          <span class="text">{{ $t('toolbar.import') }}</span>
        </div> -->
        <div class="toolbarBtn" @click="clearStorage">
          <span class="icon iconfont iconshanchu"></span>
          <span class="text">清空当前内容</span>
        </div>
        <div class="toolbarBtn" @click="() => {openTestCaseDialog = true;handleConditionSelect()}">
          <span class="icon iconfont icondaoru"></span>
          <span class="text">打开已有的自检表</span>
        </div>
        <div class="toolbarBtn" @click="saveFile">
          <span class="icon iconfont iconexport"></span>
          <span class="text">保存到服务器</span>
        </div>
        <div class="toolbarBtn" @click="emit('showExport')">
          <span class="icon iconfont iconexport"></span>
          <span class="text">{{ $t('toolbar.export') }}</span>
        </div>

        <!-- <div class="toolbarBtn" @click="emit('showShortcutKey')">
          <span class="icon iconfont iconjianpan"></span>
          <span class="text">{{ $t('toolbar.shortcutKey') }}</span>
        </div> -->
      </div>
    </div>
    <NodeImage></NodeImage>
    <NodeHyperlink></NodeHyperlink>
    <NodeIcon></NodeIcon>
    <NodeNote></NodeNote>
    <NodeTag></NodeTag>
    <Export></Export>
    <Import></Import>
    <el-dialog v-model="openTestCaseDialog" title="查找自检脑图">
      <div style="width: 100%;">
        <el-input v-model="fileName" style="width: 70%;" />
        <el-button @click="handleConditionSelect" style="width: 30%;">查找</el-button>
      </div>

      <el-table :data="fileList">
        <el-table-column property="id" label="id" width="100" align="center" />
        <el-table-column property="name" label="名称" width="200" align="center" />
        <el-table-column property="createTime" label="创建时间" width="180" align="center" />
        <el-table-column property="updateTime" label="更新时间" width="180" align="center" />
        <el-table-column property="action" label="操作" align="center">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="handleClick(scope.row)">打开</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="width: 100%;" class="buttonMiddle">
        <el-button @click="upPage" style="width: 30%; " :disabled="!upPageAble">上一页</el-button>
        <el-button @click="downPage" style="width: 30%;" :disabled="!downPageAble">下一页</el-button>
      </div>
    </el-dialog>
    <el-dialog v-model="saveTestCaseDialog" :title="isExist ? '文件已存在，修改文件' : '文件不存在，新增文件'" >
      <div style="width: 100%; display: flex;">
        <div style="width: 70%;">
        <el-input v-model="saveName" placeholder="请输入文件名称" />
        <p v-if="errorMessage" style="color: red;">名称不能为空！</p>
      </div>
      <div style="width: 30%;">
        <el-button @click="onclicksaveData" style="width: 30%;">确定</el-button>
      </div>

      </div>
      
    </el-dialog>

  </div>
</template>

<script>
import NodeImage from './NodeImage'
import NodeHyperlink from './NodeHyperlink'
import NodeIcon from './NodeIcon'
import NodeNote from './NodeNote'
import NodeTag from './NodeTag'
import Export from './Export'
import Import from './Import'
import { mapState, mapMutations } from 'vuex'
import { ElNotification } from 'element-plus'
import exampleData from 'simple-mind-map/example/exampleData'
import { getData } from '../../../api'
import bus from '@/utils/bus.js'
import { themeList } from 'simple-mind-map/src/constants/constant'
import {  selfcasesmap  } from '@/config/selfcases.js'
import { selectFiles,getContent } from '@/api/selfcases/index.js'
import { ElMessage, ElMessageBox } from 'element-plus'



/**
 * @Author: 黄原寅
 * @Desc: 工具栏
 */
let fileHandle = null
export default {
  name: 'Toolbar',
  components: {
    NodeImage,
    NodeHyperlink,
    NodeIcon,
    NodeNote,
    NodeTag,
    Export,
    Import
  },
  data() {
    return {
      activeNodes: [],
      backEnd: false,
      forwardEnd: true,
      readonly: false,
      isFullDataFile: false,
      timer: null,
      isInPainter: false,
      openTestCaseDialog: false,
      fileName: "",
      saveTestCaseDialog: false,
      saveName: "",
      isExist:  false,
      fileList: [],
      pageSizeCase: 5,
      curPage:0,
      pages : 0
             }
  },
  computed: {
    ...mapState(['isHandleLocalFile', 'isDark']),
    hasRoot() {
      return this.activeNodes.findIndex(node => {
        return node.isRoot
      })
    },
    hasGeneralization() {
      return (
        this.activeNodes.findIndex(node => {
          return node.isGeneralization
        }) !== -1
      )
    },
    upPageAble(){
     return (this.curPage<=1)?false:true;
    },
    downPageAble(){
     return (this.curPage<this.pages)?true:false;
    },
    errorMessage(){
      if(!this.saveName || this.saveName==''){
        return true;
      }else{
        return false;
      }
    }
  },
  watch: {
    isHandleLocalFile(val) {
      if (!val) {
        ElNotification.closeAll()
      }
    },
    saveTestCaseDialog(newValue, oldValue) {
      if(newValue){
        const name=localStorage.getItem(selfcasesmap.nameKey);
        if(name&&name!=''){
        this.saveName=name;
      }
      }
    },


  },
  created() {
    bus.on('mode_change', this.onModeChange)
    bus.on('node_active', this.onNodeActive)
    bus.on('back_forward', this.onBackForward)
    bus.on('write_local_file', this.onWriteLocalFile)
    bus.on('painter_start', this.onPainterStart)
    bus.on('painter_end', this.onPainterEnd)

  },
  beforeDestroy() {
    bus.off('mode_change', this.onModeChange)
    bus.off('node_active', this.onNodeActive)
    bus.off('back_forward', this.onBackForward)
    bus.off('write_local_file', this.onWriteLocalFile)
    bus.off('painter_start', this.onPainterStart)
    bus.off('painter_end', this.onPainterEnd)
  },
  methods: {
    ...mapMutations(['setActiveSidebar']),
    showNodeIcon() {
      // this.$bus.$emit('showNodeIcon')
      bus.emit('close_node_icon_toolbar')
      this.setActiveSidebar('nodeIconSidebar')
    },
    // 打开公式侧边栏
    showFormula() {
      this.setActiveSidebar('formulaSidebar')
    },
    /**
     * @Author: 黄原寅
     * @Desc: 监听模式切换
     */
    onModeChange(mode) {
      this.readonly = mode === 'readonly'
    },
    /**
     * @Author: 黄原寅
     * @Desc: 监听节点激活
     */
    onNodeActive(...args) {
      this.activeNodes = [...args[0][1]]
    },
    /**
     * @Author: 黄原寅
     * @Desc: 监听前进后退
     */
    onBackForward(index, len) {
      this.backEnd = index <= 0
      this.forwardEnd = index >= len - 1
    },
    async onpageresponse(reqBody){
      const reslist= await selectFiles(reqBody);
      this.fileList=reslist.records;
      console.log(reslist)
        // DOM更新后的回调函数
      this.curPage=reslist.current;
      this.pages=reslist.pages;
    },
    async handleConditionSelect()  {
      let reqBody   = {
              "func": this.fileName,
              "pageNum": 1,
              "pageSize": this.pageSizeCase
            }
    await this.onpageresponse(reqBody);
    },
    async upPage(){
      if(this.curPage<=1){
             return;
      }
      let reqBody   = {
              "func": this.fileName,
              "pageNum": this.curPage-1,
              "pageSize": this.pageSizeCase
            }
            await this.onpageresponse(reqBody);
    },
    async downPage(){
      let reqBody   = {
              "func": this.fileName,
              "pageNum": this.curPage+1,
              "pageSize": this.pageSizeCase
            }
            await this.onpageresponse(reqBody);

    },
    async handleClick(row){
      const resContent=await getContent({
        id:row.id
      });
      console.log(resContent);
      this.setData(resContent.content);
      this.openTestCaseDialog=false;
      localStorage.setItem(selfcasesmap.idkey,row.id);
      localStorage.setItem(selfcasesmap.nameKey,row.name);
      localStorage.setItem(selfcasesmap.fileLatestTime,row.updateTime);
    },
    saveFile(){
      const id=localStorage.getItem(selfcasesmap.idkey);
      if(id&&id!=''){
        this.isExist=true;
      }else{
        this.isExist=false;
      }
      this.saveTestCaseDialog = true;
    },
    /**
     * @Author: 黄原寅
     * @Desc: 监听本地文件读写
     */
    onWriteLocalFile(content) {
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.writeLocalFile(content)
      }, 1000)
    },

    /**
     * @Author: 黄原寅
     * @Desc: 打开本地文件
     */
    async openLocalFile() {
      try {
        let [_fileHandle] = await window.showOpenFilePicker({
          types: [
            {
              description: '',
              accept: {
                'application/json': ['.smm']
              }
            }
          ],
          excludeAcceptAllOption: true,
          multiple: false
        })
        if (!_fileHandle) {
          return
        }
        fileHandle = _fileHandle
        if (fileHandle.kind === 'directory') {
          this.$message.warning('请选择文件')
          return
        }
        this.readFile()
      } catch (error) {
        console.log('error', error)
        if (error.toString().includes('aborted')) {
          return
        }
        this.$message({
          type: 'warning',
          message: '你的浏览器可能不支持，建议使用最新版本的Chrome浏览器',
          duration: 1000
        })
      }
    },

    onPainterStart() {
      this.isInPainter = true
    },

    onPainterEnd() {
      this.isInPainter = false
    },
    clearStorage() {
      localStorage.removeItem(selfcasesmap.idkey);
      localStorage.removeItem(selfcasesmap.nameKey);
      localStorage.removeItem(selfcasesmap.fileLatestTime);
      localStorage.removeItem('SIMPLE_MIND_MAP_DATA');
      window.location.reload();
      this.isExist   = false;
    },
    /**
     * @Author: 黄原寅
     * @Desc: 读取本地文件
     */
    async readFile() {
      let file = await fileHandle.getFile()
      let fileReader = new FileReader()
      fileReader.onload = async () => {
        this.$store.commit('setIsHandleLocalFile', true)
        this.setData(fileReader.result)
        ElNotification.closeAll()
        ElNotification({
          title: '提示',
          message: `当前正在编辑你本机的【${file.name}】文件`,
          duration: 0,
          showClose: true
        })
      }
      fileReader.readAsText(file)
    },
    async onclicksaveData() {

      if(this.errorMessage){
        return;
      }
      let reqBody = {
        "name": this.saveName
      };
      const id =  localStorage.getItem(selfcasesmap.idkey);
      if(id&&id!=null&&id!='') {
        const resContent=await getContent({
        id
      });
      const update_time =  localStorage.getItem(selfcasesmap.fileLatestTime);
      console.log("数据库时间"+resContent.updateTime);
      console.log("本地存的时间"+update_time);

      if(resContent.updateTime>update_time){
        await ElMessageBox.alert('目标文件已被其他人更新，请将你的内容导出到本地，并重新在列表中打开文件', '提示', {
    // if you want to disable its autofocus
    // autofocus: false,
    confirmButtonText: 'OK',
    callback: (action) => {
    },
  })

           return;
      }


        reqBody["id"]=id;
      }
      await this.emit('saveToServer', reqBody);

      this.saveTestCaseDialog=false;
    },
    /**
     * @Author: 黄原寅
     * @Desc: 渲染读取的数据
     */
    setData(str) {
      try {
        let data = JSON.parse(str)
        if (typeof data !== 'object') {
          throw new Error('文件内容有误')
        }
        if (data.root) {
          this.isFullDataFile = true
        } else {
          this.isFullDataFile = false
          data = {
            ...exampleData,
            root: data
          }
        }
        bus.emit('setData', data)
      } catch (error) {
        console.log(error)
        this.$message.error('文件打开失败')
      }
    },

    /**
     * @Author: 黄原寅
     * @Desc: 写入本地文件
     */
    async writeLocalFile(content) {
      if (!fileHandle || !this.isHandleLocalFile) {
        return
      }
      if (!this.isFullDataFile) {
        content = content.root
      }
      let string = JSON.stringify(content)
      const writable = await fileHandle.createWritable()
      await writable.write(string)
      await writable.close()
    },

    /**
     * @Author: 黄原寅
     * @Desc: 创建本地文件
     */
    async createNewLocalFile() {
      await this.createLocalFile(exampleData)
    },

    /**
     * @Author: 黄原寅
     * @Desc: 另存为
     */
    async saveLocalFile() {
      let data = getData()
      await this.createLocalFile(data)
    },

    /**
     * @Author: 黄原寅
     * @Desc: 创建本地文件
     */
    async createLocalFile(content) {
      try {
        let _fileHandle = await window.showSaveFilePicker({
          types: [
            {
              description: '',
              accept: { 'application/json': ['.smm'] }
            }
          ]
        })
        if (!_fileHandle) {
          return
        }
        const loading = this.$loading({
          lock: true,
          text: '正在创建文件',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        fileHandle = _fileHandle
        this.$store.commit('setIsHandleLocalFile', true)
        this.isFullDataFile = true
        await this.writeLocalFile(content)
        await this.readFile()
        loading.close()
      } catch (error) {
        console.log(error)
        if (error.toString().includes('aborted')) {
          return
        }
        this.$message.warning('你的浏览器可能不支持，建议使用最新版本的Chrome浏览器')
      }
    },
    emit: (...agrs) => bus.emit(...agrs)
  }
}
</script>

<style lang="less" scoped>
.buttonMiddle {
  align-items: center;
  text-align: center;
}


.toolbarContainer {
  &.isDark {
    .toolbar {
      color: hsla(0, 0%, 100%, 0.9);

      .toolbarBlock {
        background-color: #262a2e;
      }

      .toolbarBtn {
        .icon {
          background: transparent;
          border-color: transparent;
        }

        &:hover {
          &:not(.disabled) {
            .icon {
              background: hsla(0, 0%, 100%, 0.05);
            }
          }
        }

        &.disabled {
          color: #54595f;
        }
      }
    }
  }

  .toolbar {
    position: fixed;
    left: 50%;
    transform: translateX(-50%);
    top: 20px;
    width: max-content;
    max-width: 100%;
    display: flex;
    padding: 0 20px;
    padding-top: 20px;
    font-size: 12px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: rgba(26, 26, 26, 0.8);
    z-index: 2;
    overflow-x: auto;

    .toolbarBlock {
      display: flex;
      background-color: #fff;
      padding: 10px 20px;
      border-radius: 6px;
      box-shadow: 0 2px 16px 0 rgba(0, 0, 0, 0.06);
      border: 1px solid rgba(0, 0, 0, 0.06);
      margin-right: 20px;

      &:last-of-type {
        margin-right: 0;
      }
    }

    .toolbarBtn {
      display: flex;
      justify-content: center;
      flex-direction: column;
      cursor: pointer;
      margin-right: 20px;
      flex-shrink: 0;

      &:last-of-type {
        margin-right: 0;
      }

      &:hover {
        &:not(.disabled) {
          .icon {
            background: #f5f5f5;
          }
        }
      }

      &.active {
        .icon {
          background: #f5f5f5;
        }
      }

      &.disabled {
        color: #bcbcbc;
        cursor: not-allowed;
        pointer-events: none;
      }

      .icon {
        display: flex;
        height: 26px;
        background: #fff;
        border-radius: 4px;
        border: 1px solid #e9e9e9;
        justify-content: center;
        flex-direction: column;
        text-align: center;
        padding: 0 5px;
      }

      .text {
        margin-top: 3px;
      }
    }
  }
}

@media screen and (max-width: 1040px) {
  .toolbarContainer {
    .toolbar {
      left: 20px;
      right: 20px;
      transform: translateX(0);
      width: auto;
      max-width: none;
    }
  }
}
</style>
